var app = getApp();
var md5 = require("../../utils/md5.js");
Page({
  data: {
    goodsList: {
      saveHidden: true,
      totalPrice: 0,
      allSelect: true,
      noSelect: false,
      list: []
    },
    width: wx.getStorageSync('width'),
    height: wx.getStorageSync('height'),
    shopDeliveryPrice: [],
    delBtnWidth: 120,
  },
  getEleWidth: function(w) {
    var real = 0;
    try {
      var res = wx.getSystemInfoSync().windowWidth;
      var scale = (750 / 2) / (w / 2);
      real = Math.floor(res / scale);
      return real;
    } catch (e) {
      return false;
    }
  },
  initEleWidth: function() {
    var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
    this.setData({
      delBtnWidth: delBtnWidth
    });
  },
  onLoad: function() {
    var that = this
    that.initEleWidth();
    that.setData({
      open_id: app.globalData.openId,
      user_id: app.globalData.userId,
    });
  },
  onShow: function() {
    var that = this
    that.loadData();
  },
  loadData: function() {
    var that = this;
    wx.showToast({
      title: '加载中',
      icon: 'loading'
    })
    var openid = app.globalData.openId;
    var shop_id = app.globalData.shopId;;
    var user_id = app.globalData.userId;
    var service = 'Product.GetShopCart';
    var sign = md5.md5(openid + service + shop_id + user_id);

    wx.request({
      url: app.globalData.serviceUrl + 'Product.GetShopCart',
      header: {
        'Content-Type': 'json'
      },
      data: {
        openid: openid,
        shop_id: shop_id,
        sign: sign,
        user_id: user_id,
      },
      success: function(res) {
        wx.hideToast()
        console.log(123);
        console.log(res);
        var code = res.data.data.code;
        var shopList = [];
        if (code == 0) {
          var info = res.data.data.info;
          if (info[0].product) {
            shopList = info[0].product;
          }
          console.log(shopList);
          that.data.goodsList.list = shopList
          that.setGoodsList(that.getSaveHide(), that.totalPrice(), that.allSelect(), that.noSelect(), shopList);
        } else {
          that.data.goodsList.list = []
          that.setGoodsList(that.getSaveHide(), that.totalPrice(), that.allSelect(), that.noSelect(), shopList);
        }
      },
      fail: function(res) {
        wx.hideToast()
      }
    })
  },

  toIndexPage: function() {
    wx.switchTab({
      url: "/pages/classification/index"
    });
  },

  touchS: function(e) {
    if (e.touches.length == 1) {
      this.setData({
        startX: e.touches[0].clientX
      });
    }
  },
  touchM: function(e) {
    var index = e.currentTarget.dataset.index;
    if (e.touches.length == 1) {
      var moveX = e.touches[0].clientX;
      var disX = this.data.startX - moveX;
      var delBtnWidth = this.data.delBtnWidth;
      var left = "";
      if (disX == 0 || disX < 10) { //如果移动距离小于等于0，container位置不变
        left = "margin-left:0px";
      } else if (disX > 10) { //移动距离大于0，container left值等于手指移动距离
        left = "margin-left:-" + disX + "px";
        if (disX >= delBtnWidth) {
          left = "left:-" + delBtnWidth + "px";
        }
      }
      var list = this.data.goodsList.list;
      if (index != "" && index != null) {
        list[parseInt(index)].left = left;
        this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
      }
    }
  },
  touchE: function(e) {
    var index = e.currentTarget.dataset.index;
    if (e.changedTouches.length == 1) {
      var endX = e.changedTouches[0].clientX;
      var disX = this.data.startX - endX;
      var delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var left = disX > delBtnWidth ? "margin-left:-" + delBtnWidth + "px" : "margin-left:0px";
      var list = this.data.goodsList.list;
      if (index !== "" && index != null) {
        list[parseInt(index)].left = left;
        this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);

      }
    }
  },
  delItem: function(e) {
    var index = e.currentTarget.dataset.index;
    var list = this.data.goodsList.list;
    list.splice(index, 1);
    this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
  },
  selectTap: function(e) {
    var index = e.currentTarget.dataset.index;
    var list = this.data.goodsList.list;
    if (index !== "" && index != null) {
      list[parseInt(index)].active = !list[parseInt(index)].active;
      this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
    }
  },
  totalPrice: function() {
    var list = this.data.goodsList.list;
    var total = 0;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (curItem.active) {
        total += parseFloat(curItem.product_money) * curItem.product_num;
      }
    }
    total = parseFloat(total.toFixed(2)); //js浮点计算bug，取两位小数精度
    return total;
  },
  allSelect: function() {
    var list = this.data.goodsList.list;
    var allSelect = false;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (curItem.active) {
        allSelect = true;
      } else {
        allSelect = false;
        break;
      }
    }
    return allSelect;
  },
  noSelect: function() {
    var list = this.data.goodsList.list;
    var noSelect = 0;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (!curItem.active) {
        noSelect++;
      }
    }
    if (noSelect == list.length) {
      return true;
    } else {
      return false;
    }
  },
  setGoodsList: function(saveHidden, total, allSelect, noSelect, list) {
    this.setData({
      goodsList: {
        saveHidden: saveHidden,
        totalPrice: total,
        allSelect: allSelect,
        noSelect: noSelect,
        list: list
      }
    });
    var shopCarInfo = {};
    var tempNumber = 0;
    shopCarInfo.shopList = list;
    for (var i = 0; i < list.length; i++) {
      tempNumber = tempNumber + list[i].number
    }
    shopCarInfo.shopNum = shopCarInfo.shopList.length;
    wx.setStorage({
      key: "shopCarInfo",
      data: shopCarInfo
    })
  },
  bindAllSelect: function() {
    var currentAllSelect = this.data.goodsList.allSelect;
    var list = this.data.goodsList.list;
    if (currentAllSelect) {
      for (var i = 0; i < list.length; i++) {
        var curItem = list[i];
        curItem.active = false;
      }
    } else {
      for (var i = 0; i < list.length; i++) {
        var curItem = list[i];
        curItem.active = true;
      }
    }

    this.setGoodsList(this.getSaveHide(), this.totalPrice(), !currentAllSelect, this.noSelect(), list);
  },
  jiaBtnTap: function(e) { //数量加一
    var index = e.currentTarget.dataset.index;
    var list = this.data.goodsList.list;
    if (index !== "" && index != null) {
      list[parseInt(index)].product_num++;
      this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
    }
  },
  jianBtnTap: function(e) { //数量减一
    var index = e.currentTarget.dataset.index;
    var list = this.data.goodsList.list;
    if (index !== "" && index != null) {
      if (list[parseInt(index)].product_num > 1) {
        list[parseInt(index)].product_num--;
        this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
      }
    }
  },
  editTap: function() {
    var list = this.data.goodsList.list;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      curItem.active = false;
    }
    this.setGoodsList(!this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
  },
  saveTap: function() {
    var list = this.data.goodsList.list;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      curItem.active = true;
    }
    this.setGoodsList(!this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
  },
  getSaveHide: function() {
    var saveHidden = this.data.goodsList.saveHidden;
    return saveHidden;
  },
  deleteSelected: function() {
    var that = this;
    var list = this.data.goodsList.list;
    var str = '';
    for (var i = 0; i < list.length; i++) {
      var dic = list[i];
      if (dic.active == true) {
        if (str == '') {
          str = i + '';
        } else {
          var ii = i + '';
          str = str + ',' + ii;
        }
      }
    }

    var openid = app.globalData.openId;
    var key_val = str;
    var service = 'Product.DelShopCart';
    var user_id = app.globalData.userId;
    var shop_id = app.globalData.shopId;
    var sign = md5.md5(key_val + openid + service + shop_id + user_id);

    wx.request({
      url: app.globalData.serviceUrl + 'Product.DelShopCart',
      header: {
        'Content-Type': 'json'
      },
      data: {
        openid: openid,
        key_val: key_val,
        sign: sign,
        shop_id: shop_id,
        user_id: user_id,
      },
      success: function(res) {
        var result = res.data.data;
        if (result.code == 0) {
          wx.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 2000
          })
          that.loadData();
        }
      }
    })
  },
  toPayOrder: function() {
    this.getlod();
    var that = this;
    if (that.data.goodsList.noSelect) { //没有选中的直接返回
      return;
    }
    wx.showToast({
      title: '加载中',
      icon: 'loading'
    })
    // 重新计算价格，判断库存
    var shopList = [];
    var shopCarInfoMem = that.data.goodsList;
    if (shopCarInfoMem && shopCarInfoMem.list) { //从内存中获取有效产品的购物信息
      // shopList = shopCarInfoMem.shopList
      shopList = shopCarInfoMem.list.filter(entity => {
        return entity.active;
      });
    }
    console.log('1234');
    console.log(shopList);
    if (shopList.length == 0) { //没有产品的直接返回
      wx.hideToast()
      return;
    }
    var isFail = false;
    var doneNumber = 0;
    var needDoneNUmber = shopList.length;
    for (let i = 0; i < shopList.length; i++) {
      if (isFail) {
        wx.hideToast()
        return;
      }
      let carShopBean = shopList[i];
      //获取最新价格
      var openid = app.globalData.openId;
      var product_id = carShopBean.product_id;
      var service = 'Product.GetInfo';
      var user_id = app.globalData.userId;
      var sign = md5.md5(openid + product_id + service + user_id);
      wx.request({
        url: app.globalData.serviceUrl + 'Product.GetInfo',
        header: {
          'Content-Type': 'json'
        },
        data: {
          openid: openid,
          product_id: product_id,
          sign: sign,
          user_id: user_id,
        },
        success: function(res) {
          var result = res.data.data;
          console.log('result');
          console.log(result);
          if (result.code == 0) {
            doneNumber++;
            if (result.info.product_money != carShopBean.product_money) {
              wx.showModal({
                title: '提示',
                content: result.info.product_name + ' 价格有调整，请重新购买',
                showCancel: false
              })
              isFail = true;
              wx.hideToast()
              return;
            }
          }
          if (needDoneNUmber == doneNumber) {
            that.navigateToPayOrder();
          }
        }
      })
    }
  },
  navigateToPayOrder: function() {
    var that = this;
    var shopList = that.data.goodsList.list;
    shopList = shopList.filter(entity => {
      return entity.active;
    });

    console.log(shopList);
    var pIdArr = '';
    for (var i = 0; i < shopList.length; i++) {
      var dic = shopList[i];
      if (dic.active == true) {
        if (pIdArr == '') {
          pIdArr = dic.product_id + '';
        } else {
          var product_id = dic.product_id + '';
          pIdArr = pIdArr + ',' + product_id;
        }
      }
    }

    var numArr = '';
    for (var i = 0; i < shopList.length; i++) {
      var dic = shopList[i];
      if (dic.active == true) {
        if (numArr == '') {
          numArr = dic.product_num + '';
        } else {
          var num = dic.product_num + '';
          numArr = numArr + ',' + num;
        }
      }
    }

    var service = 'Product.Buy_many';
    var openid = app.globalData.openId;
    var user_id = app.globalData.userId;
    var shop_id = app.globalData.shopId;
    var product_arr = pIdArr;
    var num_arr = numArr;
    var xcx='xcx';
    var sign = md5.md5(num_arr + openid + product_arr + service + shop_id + user_id + xcx);

    wx.request({
      url: app.globalData.serviceUrl + 'Product.Buy_many',
      header: {
        'Content-Type': 'json'
      },
      data: {
        openid: openid,
        num_arr: num_arr,
        product_arr: product_arr,
        shop_id: shop_id,
        sign: sign,
        user_id: user_id,
        xcx:xcx
      },
      success: function(res) {
        wx.hideToast()
        var result = res.data.data;
        console.log(res);
        if (result.code == 0) {
          var buyNowInfo = {};
          buyNowInfo.shop_id = app.globalData.shopId;
          buyNowInfo.order_id = result.info.order_id;
          buyNowInfo.order_num = result.info.order_num;
          buyNowInfo.order_price = result.info.order_price;
          buyNowInfo.shop_address = result.info.shop_address;
          buyNowInfo.shop_worktime = result.info.shop_worktime;
          buyNowInfo.user_tel = result.info.user_tel;
          buyNowInfo.is_delive = result.info.is_delive;
          buyNowInfo.is_dada = result.info.is_dada;
          buyNowInfo.dada_city_code = result.info.dada_city_code;
          buyNowInfo.delive_fee = result.info.delive_fee;
          buyNowInfo.total_price = result.info.order_price;
          buyNowInfo.default_address = result.info.default_address;
          buyNowInfo.goodsList = result.info.product;
          buyNowInfo.price = result.info.order_price;
          buyNowInfo.is_canhe_dis = result.info.is_canhe_dis;
          buyNowInfo.is_peisong_dis = result.info.is_peisong_dis;
          buyNowInfo.canhe_money = result.info.canhe_money;
          buyNowInfo.message = result.info.message;
          console.log(buyNowInfo)
          wx.setStorageSync('shopCarInfo', buyNowInfo);
          wx.navigateTo({
            url: "/pages/to-pay-order-many/index?orderType=buyCart"
          })
        } else {
          wx.showModal({
            title: '失败',
            content: result.msg,
            showCancel: false
          })
        }
      }
    })
  },

  getlod: function() {
    var that = this;
    var service = 'User.CheckLand';
    var open_id = app.globalData.openId;
    var user_id = app.globalData.userId;
    var sign = md5.md5(open_id + service + user_id);
    wx.request({
      url: app.globalData.serviceUrl + service,
      header: {
        'Content-Type': 'json'
      },
      data: {
        sign: sign,
        user_id: user_id,
        open_id: open_id,
      },
      success: (res) => {
        var result = res.data.data;
        if (result.code == 0) {
          if (result.info == 0) {
            app.globalData.userTel = '';
            app.globalData.userId = '';
            app.globalData.openId = '';
            app.globalData.pageFlag = false;
            wx.clearStorage();
            wx.navigateTo({
              url: "/pages/login/index"
            })
          }
        } else {
          app.globalData.userTel = '';
          app.globalData.userId = '';
          app.globalData.openId = '';
          app.globalData.pageFlag = false;
          wx.clearStorage();
          wx.navigateTo({
            url: "/pages/login/index"
          })
        }
      }
    })
  }
})